package com.framework.util.generator;

import java.util.List;

import com.framework.util.generator.db.DataSource;
import com.framework.util.generator.db.DbFactory;
import com.framework.util.generator.util.ConvertHandler;
import com.framework.util.generator.util.FileType;
import com.framework.util.generator.util.FileUtils;
import com.framework.util.generator.util.Resources;
import com.framework.util.generator.vo.Column;
import com.framework.util.generator.vo.Table;

import freemarker.template.Template;

public class GenerateCode extends AbstractGenerate implements Generate {
	FileType fileType = null;

	public GenerateCode(FileType javaFileType) {
		super();
		this.fileType = javaFileType;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.ketayao.ketacustom.generate.Generate#generate(com.ketayao.ketacustom.generate.vo.Table)
	 */
	@Override
	public void generate(Table table) throws Exception {
		model.put("tableName", table.getTableName().toLowerCase());
		model.put("columns", table.getColumns());
		// // 特殊类型处理
		handleSpecial(table.getColumns());
		Template template = cfg.getTemplate("templates" + separator + fileType.getTemplate());
		String content = FreeMarkers.renderTemplate(template, model);
		String filePath = javaPath + fileType.getJavaStorePath() + separator + Resources.TPL_CLASS_NAME
				+ fileType.getFileNameExtension();
		FileUtils.writeFile(content, filePath);
	}

	public static void main(String[] args) {
		GenerateCode generatreCode = new GenerateCode(FileType.ENTITY);
		try {
			DataSource dataSource = DbFactory.create();
			Table table = dataSource.getTable("base_user");
			ConvertHandler.tableHandle(table);
			generatreCode.generate(table);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.ketayao.ketacustom.generate.Generate#generate(java.util.List)
	 */
	@Override
	public void generate(List<Table> tables) throws Exception {
		// TODO Auto-generated method stub
	}

	/**
	 * 特殊类型处理
	 * 
	 * @param columns
	 */
	private void handleSpecial(List<Column> columns) {
		boolean hasDate = false;
		boolean hasBigDecimal = false;
		for (Column column : columns) {
			if (column.getJavaType().equals("Date")) {
				hasDate = true;
			} else if (column.getJavaType().equals("BigDecimal")) {
				hasBigDecimal = true;
			}
		}

		model.put("hasDate", hasDate);
		model.put("hasBigDecimal", hasBigDecimal);
	}
}
